package repository

import (
	"fitness/go-admin/internal/model"

	"gorm.io/gorm"
)

type PermissionRepository interface {
	Create(permission *model.Permission) error
	GetByID(id uint) (*model.Permission, error)
	GetByCode(code string) (*model.Permission, error)
	List() ([]model.Permission, error)
	Update(permission *model.Permission) error
	Delete(id uint) error
}

type permissionRepository struct {
	db *gorm.DB
}

func NewPermissionRepository(db *gorm.DB) PermissionRepository {
	return &permissionRepository{db: db}
}

func (r *permissionRepository) Create(permission *model.Permission) error {
	return r.db.Create(permission).Error
}

func (r *permissionRepository) GetByID(id uint) (*model.Permission, error) {
	var permission model.Permission
	err := r.db.First(&permission, id).Error
	return &permission, err
}

func (r *permissionRepository) GetByCode(code string) (*model.Permission, error) {
	var permission model.Permission
	err := r.db.Where("code = ?", code).First(&permission).Error
	return &permission, err
}

func (r *permissionRepository) List() ([]model.Permission, error) {
	var permissions []model.Permission
	err := r.db.Order("id ASC").Find(&permissions).Error
	return permissions, err
}

func (r *permissionRepository) Update(permission *model.Permission) error {
	return r.db.Save(permission).Error
}

func (r *permissionRepository) Delete(id uint) error {
	return r.db.Delete(&model.Permission{}, id).Error
}
